package com.college.common.utils.thread;

import com.alibaba.fastjson2.JSON;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.college.common.utils.json.FastjsonUtils;
import com.college.common.utils.log.LogPrintUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ThreadLocalContext {

	private static final ThreadLocal<Map<String, Object>> CONTEXT = new TransmittableThreadLocal<>();
	/**
	 * 是否使用 isMDC 作为本地线程的容器
	 */
	private static final boolean isMDC = true;

	/**
	 * 初始化上下文
	 */
	public static void initContext() {
		LogPrintUtils.info(log, "初始化本地线程上下文");
		Map<String, Object> con = CONTEXT.get();
		if (con == null) {
			CONTEXT.set(new HashMap<>(8));
		} else {
			CONTEXT.get().clear();
		}
		put("startTime", System.currentTimeMillis());
	}

	/**
	 * 清除上下文
	 */
	public static void clearContext() {
		LogPrintUtils.info(log, "清除本地线程上下文");
		CONTEXT.remove();
	}

	/**
	 * 获取上下文内容
	 */
	public static <T> T get(String key, Class<T> tClass) {
		if (isMDC) {
			String content = MDC.get(key);
			if (tClass.isInstance(content)) {
				return (T) content;
			}
			return FastjsonUtils.readValue(content, tClass);
		}
		Map<String, Object> con = CONTEXT.get();
		if (con == null) {
			return null;
		}
		return (T) con.get(key);
	}

	/**
	 * 设置上下文参数
	 */
	public static void put(String key, Object value) {
		if (isMDC) {
			if (value instanceof String) {
				MDC.put(key, String.valueOf(value));
			} else {
				MDC.put(key, JSON.toJSONString(value));
			}
			return;
		}
		Map<String, Object> con = CONTEXT.get();
		if (con == null) {
			CONTEXT.set(new HashMap<>(8));
			con = CONTEXT.get();
		}
		con.put(key, value);
	}


}
